<template>
  <div>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="coalType">
        <el-select
          multiple
          clearable
          v-model="queryParams.coalType"
          placeholder="请选择"
          class="!w-300px"
        >
          <el-option
            v-for="dict in coalTypeList"
            :key="dict.id"
            :label="dict.coalName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易方式" prop="tradingWay">
        <el-select clearable v-model="queryParams.tradingWay" placeholder="请选择" class="!w-300px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BID_TRADING_WAY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标段大小" prop="sectionSize">
        <el-select
          multiple
          clearable
          v-model="queryParams.sectionSize"
          placeholder="请选择"
          class="!w-300px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BID_SECTION_SIZE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-card class="mt-20px" v-loading="chartLoading">
      <section class="flex space-x-12">
        <div class="h-350px w-full">
          <Echart
            :height="350"
            :options="candlestickOptionData"
            @dataZoomReady="chartDataZoom"
            @initReady="initCandlestick"
          />
        </div>
      </section>
    </el-card>
    <el-card class="mt-20px">
      <!-- 列表 -->
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
        :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
      >
        <el-table-column label="序号" align="center" width="60" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          label="时间"
          align="center"
          prop="localDate"
          min-width="150"
          fixed="left"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="最高溢价(元/吨)"
          align="center"
          prop="highestPrice"
          min-width="150"
        />
        <el-table-column
          label="最低溢价(元/吨)"
          align="center"
          prop="bottomPrice"
          min-width="150"
        />
        <el-table-column
          label="开始价格(元/吨)"
          align="center"
          prop="startAveragePrice"
          min-width="150"
        />
        <el-table-column
          label="结束价格(元/吨)"
          align="center"
          prop="endAveragePrice"
          min-width="150"
        />
        <el-table-column
          label="涨跌指数(%)"
          align="center"
          prop="roseAndFallIndex"
          min-width="150"
        />
      </el-table>
      <el-pagination
        small
        background
        :total="total"
        layout="prev, pager, next"
        v-model:page-size="queryParams.pageSize"
        v-model:current-page="queryParams.pageNo"
        @current-change="getPremiumIndexPage"
        class="mt-20px flex justify-end"
      />
    </el-card>
  </div>
</template>
<script setup lang="ts" name="premiumIndexAnalysis">
import * as Utils from '@/utils/dict'
import * as dataCenter from '@/api/dataCenter'
import { EChartsOption } from 'echarts'
import { candlestickOption } from '../echarts-data'
import { cloneDeep } from 'lodash-es'
import { dateArrayJoin } from '@/utils/common'

const loading = ref(true) // 列表的加载中
const chartLoading = ref(true) // 列表的加载中
const total = ref(0)
const list = ref([]) // 列表的数据
const queryFormRef = ref()
const message = useMessage()
const candlestickChart = ref()
const coalTypeList: Record<string, any> = ref([])
const candlestickOptionData = reactive<EChartsOption>(candlestickOption) as EChartsOption
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  coalType: [],
  tradingWay: undefined,
  sectionSize: []
})
const { DICT_TYPE, getIntDictOptions, getStrDictOptions } = reactive(Utils)
let startTime = ''
let dateList: any[] = []
let dataList: any[] = []
let candDateList: any[] = []
let candDataList: any[] = []

/** 查询列表 */

const getList = async () => {
  getPremiumIndex()
  getPremiumIndexPage()
}

const getBodyData = () => {
  const data: Record<string, any> = cloneDeep(queryParams.value)
  if (!data?.tradingWay) {
    delete data.tradingWay
  }
  if (!data?.sectionSize?.length) {
    delete data.sectionSize
  }
  if (data?.coalType?.length) {
    data.coalId = data.coalType.join(',')
  }
  if (data?.sectionSize?.length) {
    data.sectionSize = data.sectionSize.join(',')
  }
  delete data.coalType
  return data
}

const getPremiumIndex = async () => {
  chartLoading.value = true
  try {
    const data: Record<string, any> = cloneDeep(getBodyData())
    delete data.pageNo
    delete data.pageSize
    if (startTime) {
      data['startTime'] = startTime
    }
    const res = await dataCenter.getPremiumIndex(data)
    initCandlestickData(res)
  } finally {
    chartLoading.value = false
  }
}

const getPremiumIndexPage = async () => {
  loading.value = true
  try {
    const res = await dataCenter.getPremiumIndexPage(getBodyData())
    total.value = res?.total || 0
    list.value = handleList(res?.priceIndexResultDataList || [])
  } finally {
    loading.value = false
  }
}

const handleList = (list) => {
  return list.map((e) => {
    e.localDate = dateArrayJoin(e.localDate)
    return e
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  startTime = ''
  candDateList = []
  candDataList = []
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const initCandlestick = (chart) => {
  candlestickChart.value = chart
}

const chartDataZoom = async (event) => {
  if (event.start === 0 && !chartLoading.value) {
    startTime = candDateList[0]
    await getPremiumIndex()
    setSchedule(event)
  }
}

const setSchedule = (event: Record<string, any>) => {
  let start = 0
  let end = 0
  if (dateList?.length) {
    const schedule = event.end - event.start
    start = 50 / candDateList.length
    end = start + schedule
  } else {
    start = event.start
    end = event.end
    message.warning('暂无数据了')
  }
  toRaw(candlestickChart.value)?.setOption({
    dataZoom: [
      {
        start,
        end
      }
    ]
  })
}

const initCandlestickData = (data) => {
  dateList =
    data.localDateList?.map((e) => {
      return dateArrayJoin(e)
    }) || []
  dataList = data.priceDataList || []
  candDateList = [...dateList, ...candDateList]
  candDataList = [...dataList, ...candDataList]
  toRaw(candlestickChart.value)?.setOption({
    title: {
      text: ''
    },
    grid: {
      top: 30
    },
    tooltip: {
      formatter: (params) => {
        const data = params[0].data
        return (
          params[0].name +
          '<br>' +
          '开始价格:' +
          data[1] +
          '(元/吨)<br>' +
          '结束价格:' +
          data[2] +
          '(元/吨)<br>' +
          '最低溢价:' +
          data[3] +
          '(元/吨)<br>' +
          '最高溢价:' +
          data[4] +
          '(元/吨)'
        )
      }
    },
    xAxis: {
      data: candDateList
    },
    series: [
      {
        data: candDataList
      }
    ],
    dataZoom: [
      {
        type: 'slider',
        left: 75,
        start: 50,
        end: 100,
        height: 16,
        handleSize: '100%',
        moveHandleSize: 14
      }
    ]
  })
}

const bidCoalManageList = async () => {
  const res = await dataCenter.bidCoalManageList()
  coalTypeList.value = res || []
}

/** 初始化 **/
onMounted(() => {
  bidCoalManageList()
  getList()
})
</script>
